<template>
  <el-dialog
    v-model="dialogVisible"
    title="加载页面"
    width="600px"
    class="load-dialog"
  >
    <div class="saved-pages">
      <div v-if="savedPages.length === 0" class="empty-state">
        <el-icon class="empty-icon"><DocumentDelete /></el-icon>
        <p>暂无保存的页面</p>
      </div>

      <div v-else class="pages-list">
        <div
          v-for="page in savedPages"
          :key="page.key"
          class="page-item"
          @click="selectPage(page)"
          :class="{ active: selectedPage?.key === page.key }"
        >
          <div class="page-info">
            <div class="page-name">{{ page.name }}</div>
            <div class="page-meta">
              <span>{{ page.componentCount }} 个组件</span>
              <span>{{ formatDate(page.timestamp) }}</span>
            </div>
          </div>
          <div class="page-actions">
            <el-button size="small" type="danger" @click.stop="deletePage(page)">
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
        type="primary"
        :disabled="!selectedPage"
        @click="loadSelectedPage"
      >
        加载页面
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { DocumentDelete } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: { type: Boolean, default: false }
})

const emit = defineEmits(['update:modelValue', 'load'])

const dialogVisible = ref(false)
const selectedPage = ref(null)
const savedPages = ref([])

watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    loadSavedPages()
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:modelValue', newVal)
  if (!newVal) {
    selectedPage.value = null
  }
})

const loadSavedPages = () => {
  savedPages.value = []
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    if (key && key.startsWith('page_')) {
      try {
        const pageData = JSON.parse(localStorage.getItem(key))
        savedPages.value.push({
          key,
          name: pageData.name,
          componentCount: pageData.components?.length || 0,
          timestamp: pageData.timestamp,
          data: pageData
        })
      } catch (error) {
        console.warn('解析页面数据失败:', error)
      }
    }
  }

  // 按时间倒序排列
  savedPages.value.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
}

const selectPage = (page) => {
  selectedPage.value = page
}

const loadSelectedPage = () => {
  if (selectedPage.value) {
    emit('load', selectedPage.value.data)
  }
}

const deletePage = async (page) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除页面 "${page.name}" 吗？`,
      '删除页面',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    localStorage.removeItem(page.key)
    loadSavedPages()
    ElMessage.success('页面已删除')
  } catch {
    // 用户取消删除
  }
}

const formatDate = (timestamp) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

onMounted(() => {
  loadSavedPages()
})
</script>

<style lang="scss" scoped>
.saved-pages {
  min-height: 300px;
  max-height: 400px;
  overflow-y: auto;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;

  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    color: #c0c4cc;
  }
}

.pages-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.page-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: #409eff;
    background: #f0f8ff;
  }

  &.active {
    border-color: #409eff;
    background: #e6f7ff;
  }
}

.page-info {
  flex: 1;

  .page-name {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }

  .page-meta {
    display: flex;
    gap: 12px;
    font-size: 12px;
    color: #909399;
  }
}
</style>
